﻿using System;
using System.Collections;
using System.Web;
using visinia.SmartEngine;
using viWiki.Controllers;

namespace viWiki.HttpModules
{
    /// <summary>
    /// The wiki url rewriter
    /// </summary>
    public class UrlRewriter : BaseUrlRewriter
    {
        public override string RewriteUrl(HttpApplication httpApp, IEnumerator urlEnum)
        {
            HttpContext context = ((HttpApplication)httpApp).Context;
            return HandleURL(context, urlEnum);
        }
        
        /*****************************************************************************************/
        // Wiki URL             = Wiki.aspx
        /*****************************************************************************************/
        // Wiki Page URL = Wiki/WikiPageId/Namespace/some.thing.imp.aspx        
        /*****************************************************************************************/        
        
        private string HandleURL(HttpContext context, IEnumerator urlEnum)        
        {
            string root = WebRoots.GetRelativeWebRoot;            
            if (!urlEnum.MoveNext())
                { // Wiki URL = Wiki.aspx
                    return root + "Default.aspx?PageId=" + WikiController.WikiWebPageId;
                }
                // display the Wiki page
                int wikipageid = 0;
                if (Int32.TryParse(TrimExtension((string)urlEnum.Current), out wikipageid))
                {
                    if (WikiPageController.GetWikiPage(wikipageid) != null)
                        return root + "Default.aspx?PageId=" + WikiController.WikiWebPageId + "&WikiPageId=" + wikipageid;
                }
            return null;
        }

        private string TrimExtension(string url)
        {
            if (url.EndsWith(".aspx"))
                return url.Remove(url.LastIndexOf('.'));
            else
                return url;
        }
    }
}
